package com.dyna.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import com.dyna.foundation.domain.entity.SysDictType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 字典工具类
 * @author zhoucaiwang
 * @date 2023/10/21
 */
public class DictUtil {

    /** 使用本地变量隔绝不同请求之间的操作 */
    private static ThreadLocal<Map<String, Map<String, String>>> THREADLOCAL_MAP = new ThreadLocal<>();

    /**
     * 初始化字典 THREAD_LOCAL_MAP
     */
    public static void initDictMap(String dictType) {
        Assert.notBlank(dictType, "字典类型不能为空");
        Map<String, Map<String, String>> map = THREADLOCAL_MAP.get();
        if (MapUtil.isEmpty(map)) {
            map = new HashMap<>();
            THREADLOCAL_MAP.set(map);
        }
        Map<String, String> dictTypeMap = map.get(dictType);
        if (MapUtil.isEmpty(dictTypeMap)) {
            List<SysDictType> dictDataByType = DictLocalCacheUtil.getDictDataByType(dictType);
            if (CollUtil.isNotEmpty(dictDataByType)) {
//                Map<String, String> dictData = dictDataByType.stream().collect(Collectors.toMap(SysDictType::getDictValue, SysDictType::getDictLabel));
                HashMap<String, String> dictData = new HashMap<>();
                map.put(dictType, dictData);
            }
        }
    }

    /**
     * 根据字典value获取字典label
     * @param dictType 字典类型
     * @param dictValue dictValue
     * @return String
     */
    public static String getDictName(String dictType, String dictValue) {
        initDictMap(dictType);
        Map<String, Map<String, String>> map = THREADLOCAL_MAP.get();
        Map<String, String> dictTypeMap = map.get(dictType);
        if (MapUtil.isNotEmpty(dictTypeMap)) {
            String lable = dictTypeMap.get(dictValue);
            return lable;
        }
        return null;
    }

    /**
     * 清理本地线程字典类型数据
     * @param dictType 字典类型
     */
    public static void clear(String dictType) {
        Map<String, Map<String, String>> map = THREADLOCAL_MAP.get();
        Map<String, String> dictMap = map.get(dictType);
        if (MapUtil.isNotEmpty(dictMap)) {
            dictMap.remove(dictType);
        }
    }

}
